package com.platform.tony.config;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.platform.tony.ext.UserExt;
import com.platform.tony.dto.UserDto;
import com.platform.tony.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 邮箱认证
 */
@Slf4j
public class EmailAuthProvider implements AuthenticationProvider {

    private UserService userService;

    public EmailAuthProvider(UserService userService) {
        this.userService = userService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String name = authentication.getName();
        log.info("email name is {}", name);

        UserDto dto = null;
        try {
            UserExt user = this.userService.queryUserInfoByEmail(name);
            if (ObjectUtil.isEmpty(user)) {
                throw new UsernameNotFoundException("用户不存在!");
            }
            log.info("user info is {}", JSONObject.toJSONString(user));
            dto = new UserDto();
            dto.setId(user.getId());
            dto.setUsername(user.getUsername());
            dto.setRoles(user.getRoleList());
            dto.setEnabled(user.getStatus() == 1);

        } catch (UsernameNotFoundException notFound) {
            throw notFound;
        } catch (Exception exception) {
            throw new InternalAuthenticationServiceException(exception.getMessage(), exception);
        }

        EmailAuthToken token = new EmailAuthToken(dto, dto.getAuthorities());
        token.setDetails(authentication.getDetails());
        SecurityContextHolder.getContext().setAuthentication(token);
        return token;

    }

    /**
     * 手机登录方式
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return EmailAuthToken.class.isAssignableFrom(authentication);
    }
}
